package net.zjitc.security;

import cn.hutool.json.JSONUtil;
import net.zjitc.common.ResponseResult;
import net.zjitc.exception.CaptchaException;
import net.zjitc.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 毛钰深
 * @create 2022/1/27
 * 用户退出成功后,对jwt的操作.可以将token的信息托管给redis来处理,退出时删除缓存即可(尚未修改)
 */
@Component
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //如果认证的身份凭证存在的话,则需要手动登出
        if (authentication != null) {
            //通过 内部退出处理器 来退出
            new SecurityContextLogoutHandler().logout(httpServletRequest, httpServletResponse, authentication);
        }

        //设置响应头
        httpServletResponse.setContentType("application/json;charset-UTF-8");
        //设置响应头中的信息为空
        httpServletResponse.setHeader(jwtUtils.getHeader(), "");
        //获取response的输出流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        ResponseResult res = new ResponseResult<>();
        res.setSuccess("退出成功");
        //使用工具类将res的数据写到输出流中并返回
        outputStream.write(JSONUtil.toJsonStr(res).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();

    }
}
